package cn.itcast.order.interceptor;

import cn.itcast.order.web.ijpay.ijpayconfig.IJPayApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description IJPay线程配置绑定拦截器
 * @author sxt
 * @date 2024/4/28 17:28
 * @version 1.0
 */
@Slf4j
public class IJPayInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            // bean: controller 对象
            Object bean = ((HandlerMethod) handler).getBean();
            if (bean instanceof IJPayApiConfig) {
                IJPayApiConfig<?> config = (IJPayApiConfig<?>) bean;
                log.info("向当前请求线程绑定默认支付配置");
                config.setThreadLocalApiConfigConfig();
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            Object bean = ((HandlerMethod) handler).getBean();
            if (bean instanceof IJPayApiConfig) {
                IJPayApiConfig<?> config = (IJPayApiConfig<?>) bean;
                log.info("从当前请求线程移除默认支付配置");
                config.removeThreadLocalApiConfig();
            }
        }
    }
}
